<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="拍品管理" name="qualityControl">
                        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
                            <el-form-item label="商品名称" prop="styleName">
                                <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable
                                    style="width: 220px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="类目" prop="category">
                                <el-cascader ref="categoryRef" v-model="queryParams.category" :props="categoryProps"
                                    style="width: 220px" @change="handleChange" placeholder="请选择类目" />
                            </el-form-item>
                            <el-form-item label="审核状态" prop="auditStatu">
                                <el-select v-model="queryParams.auditStatu" placeholder="请选择审核状态" clearable
                                    @change="auditStatuChange" style="width: 220px">
                                    <el-option v-for="dict in auditStatusList" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="商品编码" prop="styleCode">
                                <el-input v-model="queryParams.styleCode" placeholder="请输入商品编码" clearable
                                    style="width: 220px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="供应商" prop="supplierName">
                                <!-- <el-select v-model="queryParams.supplierName" placeholder="请选择供应商" clearable
                                    style="width: 220px">
                                    <el-option v-for="dict in hm_supplier_type" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select> -->
                                <el-select-v2 v-model="queryParams.supplierName" filterable clearable
                                    :options="supplierNameOptions" placeholder="请选择供应商" style="width: 220px" />
                            </el-form-item>
                            <el-form-item label="拍品结果" prop="cooperationMode">
                                <el-select v-model="queryParams.cooperationMode" placeholder="请选择拍品结果" clearable
                                    style="width: 220px">
                                    <el-option v-for="dict in cooperationModeList" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="招商部" prop="recruiterDept">
                                <el-select v-model="queryParams.recruiterDept" placeholder="请选择招商部" clearable
                                    @change="deptChange" style="width: 220px">
                                    <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                        :value="dict.deptId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="招商员" prop="recruiter">
                                <el-select v-model="queryParams.recruiter" placeholder="请选择招商员" clearable
                                    style="width: 220px">
                                    <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.userName"
                                        :value="dict.userId" />
                                </el-select>
                            </el-form-item>

                        </el-form>
                        <el-form-item>
                            <el-button type="primary" @click="handleQuery">查询</el-button>
                            <el-button @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <!-- <el-col :span="1.5">
                        <el-button type="primary" @click="">拍品录入</el-button>
                    </el-col> -->
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="supplierAddProductsList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="供应商" align="center" prop="supplierName" />
                <el-table-column label="商品名称" align="center" prop="styleName">
                    <template #default="scope">
                        <div class="color_theme">{{ scope.row.styleName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="商品编码" align="center" prop="styleCode" />
                <el-table-column label="商品主图" align="center" prop="productImage" width="100">
                    <template #default="scope">
                        <image-preview :src="scope.row.productImage" :width="50" :height="50" />
                    </template>
                </el-table-column>
                <el-table-column label="类目" align="center" prop="categoryName">

                </el-table-column>
                <el-table-column label="品牌" align="center" prop="brand">
                    <template #default="scope">
                        {{ handleFilterBrand(scope.row.brand, brandList) }}
                    </template>
                </el-table-column>
                <el-table-column label="店铺名称" align="center" prop="storeName" />
                <el-table-column label="店铺ID" align="center" prop="shopId" />
                <el-table-column label="售卖主播" align="center" prop="likePerson">
                    <template #default="scope">
                        <dict-tag :options="hm_anchor" :value="scope.row.likePerson" />
                    </template>
                </el-table-column>
                <el-table-column label="售卖链接" align="center" prop="saleLink" show-overflow-tooltip>
                    <template #default="scope">
                        <el-link :href="scope.row.saleLink" type="primary" target="_blank">{{ scope.row.saleLink
                            }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="拍品结果" align="center" prop="" />
                <el-table-column label="拍品员" align="center" prop="" />
                <el-table-column label="直播机制" align="center" prop="liveStreamingMechanism" />
                <el-table-column label="是否破价" align="center" prop="discountPrice" />
                <el-table-column label="佣金" align="center" prop="commission" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleInfo(scope.row)" class="color_theme">
                            查看详情</el-button>
                        <el-button link type="primary" @click="lotRecords(scope.row)" class="color_theme"
                            style="margin-left: 0px !important"> 拍品录入</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!--拍品详情抽屉 -->
        <commoditydetails @doClose="commoditydetailsClose" :commoditydetailsData="commoditydetailsData"
            :dialogInfoVisible="dialogInfoVisible" :type="'lot'"></commoditydetails>
        <!-- 拍品记录 -->
        <lotRecord @doClose="lotRecordClose" :lotRecordData="lotRecordData" :lotRecordVisible="lotRecordVisible">
        </lotRecord>
    </div>
</template>
<script setup name="Lot" lang="ts">
import lotRecord from './components/lotRecord.vue'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { QualityControlForm, QualityControlQuery } from '@/api/group/qualityControl/types';
import { listSupplierAddProduct, getSupplierAddProducts, getproductscategorychildlistbypid } from '@/api/system/supplierAddProducts';
import { SupplierAddProductsVO } from '@/api/system/supplierAddProducts/types';
import commoditydetails from '../components/commoditydetails.vue'
import { anchorSupplierIntention, getDeptList, getUserById } from '@/api/group/qualityControl'
import { BrandVO } from '@/api/system/brand/types';
import { listBrand } from '@/api/system/brand';
import { hmSupplierList } from '@/api/group/supplier/index'
const { hm_anchor } = toRefs<any>(proxy?.useDict('hm_anchor'));
const { hm_supplier_type } = toRefs<any>(proxy?.useDict('hm_supplier_type'));

const supplierNameOptions = ref<any[]>([])
const activeTab = ref('qualityControl');
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const supplierAddProductsList = ref<SupplierAddProductsVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const ids = ref<Array<string | number>>([]);
const commoditydetailsData = ref<QualityControlForm>({})
const dialogInfoVisible = ref(false)
const lotRecordData = ref<QualityControlForm>({})
const lotRecordVisible = ref(false)
const brandList = ref<BrandVO[]>([]);
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; userName: string; }[]>([])
const categoryRef = ref();

const initFormData: QualityControlForm = {
    id: undefined,
    auditing: undefined
};
const data = reactive<PageData<QualityControlForm, QualityControlQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        styleCode: undefined,
        category: undefined,
        supplierName: undefined,
        styleName: undefined,
        cooperationMode: undefined,
        recruiterDept: undefined,
        recruiter: undefined,
        price: undefined,
        contractStatus: undefined,
        auditor: undefined,
        commission: undefined,
        auditStatus: undefined,
        auditStatu: undefined
    },
    rules: {}
});
const { queryParams, form, rules } = toRefs(data);

const auditStatusList = reactive([
    { label: '待审核', value: '1' },
    { label: '未通过', value: '2' },
    { label: '审核通过', value: '3' },
    { label: '待寄样', value: '4' },
    { label: '无货', value: '5' },
    { label: '寄样中', value: '6' },
    { label: '已入库', value: '7' },
    { label: '补样邀约', value: '8' },
    { label: '破损补样邀约', value: '9' },
    { label: '招商部退还', value: '10' },
]);

const cooperationModeList = ref([
    {
        label: '测试拍品结果1', value: '0'
    }
])
/**
 * 获取供应商列表
 */
 const getHmSupplierList = async() =>{
    const res = await hmSupplierList()
    supplierNameOptions.value = res.rows.map((item: any)=>(
        {
            label: item.supplierName,
            value: item.userId
        }
    ))
}
/**
 * 拍品记录
 */
const lotRecords = async (row?: SupplierAddProductsVO) => {
    const _id = row?.id || ids.value[0];
    const res: any = await getSupplierAddProducts(_id);
    lotRecordVisible.value = true;
    lotRecordData.value = res.data
}
/**
 * 拍品记录关闭
 */
const lotRecordClose = () => {
    lotRecordVisible.value = false;
    getList()
}
// 类目请求方法封装
const ategoryQuest = (pid: string | number, level: any, resolve: (data: any) => void) => {
    getproductscategorychildlistbypid({ pid: pid }).then(res => {
        const datas = res.rows.map((value: { categoryId: string, categoryName: string }) => ({
            value: value.categoryId,
            label: value.categoryName,
            // leaf: level >= 3
        }));
        resolve(datas);
    })
}

// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
    if (val) {

        categoryRef.value.togglePopperVisible()
        queryParams.value.category = val[val.length - 1]
        queryParams.value.firstCategory = val[0]
        queryParams.value.secondCategory = val[1]
        queryParams.value.thirdCategory = val[2]
        queryParams.value.fourthCategory = val[3]
    }
}

// 类目props
const categoryProps = reactive({
    lazy: true,
    checkStrictly: true,
    lazyLoad(node: any, resolve: (data: any) => void) {
        const { level } = node
        const pid = !level ? 0 : node.value
        ategoryQuest(pid, level, resolve)
    }
})

/**
 * 品牌检索value
 * @param para 
 * @param dict 
 */
const handleFilterBrand = (para: string | number | undefined, dict: Array<any>) => {
    let _label = '';
    dict.forEach((item: any) => {
        if (item.id == String(para)) {
            _label = item.brandName;
        }
    });
    return _label;
};

/**
 * 获取品牌信息
 */
const getListBrand = async () => {
    const res = await listBrand()
    brandList.value = res.rows;
}

/**
 * 获取招商部门信息
 */
const getDeptLists = async () => {
    const res = await getDeptList({ parentId: '1782395704411734018' })
    deptList.value = res.data
}

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserById(event)
        recruiterList.value = res.data
        queryParams.value.recruiter = undefined
    } else {
        recruiterList.value = []
        queryParams.value.recruiter = undefined
    }
}

/**
 * 审核状态搜索
 */
const auditStatuChange = (value: string) => {
    queryParams.value.pageNum = 1;
    queryParams.value.auditStatus = value;
};

/** 查询供应商添加商品列表 */
const getList = async () => {
    try {
        loading.value = true;
        const res = await listSupplierAddProduct(queryParams.value);
        supplierAddProductsList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    } catch (e) {
    } finally {
        loading.value = false;
    }
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.auditStatus = '1,2,3,4,5,6,7,8,9';
    handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SupplierAddProductsVO[]) => {
    ids.value = selection.map((item) => item.id);
};

/** 查看商品详情 */
const handleInfo = (row?: SupplierAddProductsVO) => {
    nextTick(async () => {
        const _id = row?.id || ids.value[0];
        const res: any = await getSupplierAddProducts(_id);
        dialogInfoVisible.value = true;
        commoditydetailsData.value = res.data
    });
};
/** 商品详情关闭 */
const commoditydetailsClose = () => {
    dialogInfoVisible.value = false;
}


onMounted(() => {
    queryParams.value.auditStatus = '1,2,3,4,5,6,7,8,9';
    queryParams.value.pageNum = 1;
    getDeptLists();
    getListBrand();
    getHmSupplierList();
    getList();
});
</script>
<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}
</style>